/**
 * Created by chenyong on 2015/4/26.
 */

var jwt = require('jwt-simple'),
    config = require('../config');

//验证token是否有效
function isValidatedToken(req,res,next)
{
    if(req.query && req.query.hasOwnProperty('access_token')) {
        req.headers.authorization = 'Bearer ' + req.query.access_token;
    }
    if (!req.headers || !req.headers.authorization)
    {
        return res.status(401.3).json({errcode:'100014',errmsg:'缺少access_token'});
    }

    var token = req.headers.authorization.substring(7, req.headers.authorization.length);
    var decoded = jwt.decode(token, config.azure.adal.signing_cert, 'RS256');

    if (config.azure.adal.audience.indexOf(decoded.appid) >= 0 && new Date().getTime() / 1000 < decoded.exp)
    {
        next();
    }
    else
    {
        return res.status(401.3).json({errcode:'100014',errmsg:'access_token无效'});
    }
}

exports.isValidatedToken = isValidatedToken;